package com.bookcloud.java21.aitools.aie06;

import java.awt.*;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

/** Sign-in Statistics Report UI Panel 签到统计报表界面 */
public class SignStaticsReportUI extends JPanel {

  private JTable statisticsTable;
  private DefaultTableModel tableModel;
  private JButton printButton;

  // Table column names - using 4 columns repeated 3 times for the multi-column layout
  private final String[] columnNames = {
    "姓名", "签到", "未签", "签到率",
    "姓名", "签到", "未签", "签到率",
    "姓名", "签到", "未签", "签到率"
  };

  // Color constants
  private static final Color HEADER_BG_COLOR = new Color(135, 206, 235); // Sky blue
  private static final Color TABLE_BG_COLOR = Color.WHITE;
  private static final Color BORDER_COLOR = Color.GRAY;
  private static final Color BUTTON_COLOR = new Color(70, 130, 180); // Steel blue

  public SignStaticsReportUI() {
    initializeComponents();
    layoutComponents();
    loadStatisticsData();
    setupEventHandlers();
  }

  /** Initialize all UI components 初始化所有UI组件 */
  private void initializeComponents() {
    // Create table model and table
    tableModel =
        new DefaultTableModel(columnNames, 0) {
          @Override
          public boolean isCellEditable(int row, int column) {
            return false; // Make table read-only
          }
        };

    statisticsTable = new JTable(tableModel);
    setupTable();

    // Create chart button
    printButton = new JButton("图表");
    styleButton(printButton);
  }

  /** Setup table properties and appearance 设置表格属性和外观 */
  private void setupTable() {
    // Set table properties
    statisticsTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    statisticsTable.setRowHeight(30);
    statisticsTable.setShowGrid(true);
    statisticsTable.setGridColor(BORDER_COLOR);
    statisticsTable.setBackground(TABLE_BG_COLOR);
    statisticsTable.setSelectionBackground(new Color(184, 207, 229));

    // Set column widths - each group of 4 columns should be equal
    int[] columnWidths = {80, 50, 50, 60, 80, 50, 50, 60, 80, 50, 50, 60};
    for (int i = 0; i < columnWidths.length && i < statisticsTable.getColumnCount(); i++) {
      statisticsTable.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
      statisticsTable.getColumnModel().getColumn(i).setMinWidth(columnWidths[i]);
    }

    // Setup table header
    JTableHeader header = statisticsTable.getTableHeader();
    header.setFont(new Font("微软雅黑", Font.BOLD, 13));
    header.setBackground(HEADER_BG_COLOR);
    header.setForeground(Color.BLACK);
    header.setPreferredSize(new Dimension(0, 35));
    header.setReorderingAllowed(false);

    // Center align all cells
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment(JLabel.CENTER);
    for (int i = 0; i < statisticsTable.getColumnCount(); i++) {
      statisticsTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
    }

    // Alternating row colors
    statisticsTable.setDefaultRenderer(Object.class, new AlternatingRowRenderer());
  }

  /** Layout all components 布局所有组件 */
  private void layoutComponents() {
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    setBackground(Color.WHITE);

    // Create main panel with table
    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.setBorder(
        BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(BORDER_COLOR, 2),
            "签到统计报表",
            0,
            0,
            new Font("微软雅黑", Font.BOLD, 16)));
    mainPanel.setBackground(Color.WHITE);

    // Add table in scroll pane
    JScrollPane scrollPane = new JScrollPane(statisticsTable);
    scrollPane.setBackground(Color.WHITE);
    scrollPane.getViewport().setBackground(Color.WHITE);
    scrollPane.setPreferredSize(new Dimension(0, 400));

    mainPanel.add(scrollPane, BorderLayout.CENTER);

    // Bottom panel with print button
    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    bottomPanel.setBackground(Color.WHITE);
    bottomPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
    bottomPanel.add(printButton);

    add(mainPanel, BorderLayout.CENTER);
    add(bottomPanel, BorderLayout.SOUTH);
  }

  /** Style button appearance 设置按钮样式 */
  private void styleButton(JButton button) {
    button.setFont(new Font("微软雅黑", Font.BOLD, 14));
    button.setBackground(BUTTON_COLOR);
    button.setForeground(Color.WHITE);
    button.setPreferredSize(new Dimension(80, 35));
    button.setBorder(BorderFactory.createRaisedBevelBorder());
    button.setFocusPainted(false);
    button.setCursor(new Cursor(Cursor.HAND_CURSOR));
  }

  /** Setup event handlers 设置事件处理器 */
  private void setupEventHandlers() {
    printButton.addActionListener(
        e -> {
          openChartInterface();
        });
  }

  /** Open chart interface in a new window 在新窗口中打开图表界面 */
  private void openChartInterface() {
    // Create a new frame for the chart
    JFrame chartFrame = new JFrame("学生统计图表");
    chartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    chartFrame.setSize(900, 600);
    chartFrame.setLocationRelativeTo(this);

    // Create and add the chart UI
    SignStatisticalChartUI chartUI = new SignStatisticalChartUI();
    chartFrame.add(chartUI);

    // Show the chart window
    chartFrame.setVisible(true);
  }

  /** Load statistics data into table 加载统计数据到表格 */
  private void loadStatisticsData() {
    // Clear existing data
    tableModel.setRowCount(0);

    // Get statistics data from DataUtil
    List<StudentStatistics> statisticsList = DataUtil.getStudentStatistics();

    // Calculate how many rows we need (3 students per row)
    int studentsPerRow = 3;
    int totalRows = (int) Math.ceil((double) statisticsList.size() / studentsPerRow);

    // Add data to table in 3-column format
    for (int row = 0; row < totalRows; row++) {
      Object[] rowData = new Object[12]; // 4 columns × 3 students = 12 columns

      for (int col = 0; col < studentsPerRow; col++) {
        int studentIndex = row * studentsPerRow + col;
        int colOffset = col * 4; // Each student takes 4 columns

        if (studentIndex < statisticsList.size()) {
          StudentStatistics stats = statisticsList.get(studentIndex);
          rowData[colOffset] = stats.getName();
          rowData[colOffset + 1] = stats.getSignedDays();
          rowData[colOffset + 2] = stats.getAbsentDays();
          rowData[colOffset + 3] = String.format("%.1f%%", stats.getAttendanceRate());
        } else {
          // Fill empty cells
          rowData[colOffset] = "";
          rowData[colOffset + 1] = "";
          rowData[colOffset + 2] = "";
          rowData[colOffset + 3] = "";
        }
      }

      tableModel.addRow(rowData);
    }
  }

  /** Refresh data and update display 刷新数据并更新显示 */
  public void refreshData() {
    loadStatisticsData();
  }

  /**
   * Custom cell renderer for alternating row colors and student name column highlighting
   * 交替行颜色和学生姓名列高亮的自定义单元格渲染器
   */
  private class AlternatingRowRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      Component c =
          super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

      setHorizontalAlignment(JLabel.CENTER);

      if (!isSelected) {
        // Check if this is a student name column (columns 0, 4, 8)
        boolean isStudentNameColumn = (column == 0 || column == 4 || column == 8);

        if (isStudentNameColumn) {
          // Set gray background for student name columns
          c.setBackground(new Color(220, 220, 220)); // Light gray
        } else {
          // Apply alternating row colors for other columns
          if (row % 2 == 0) {
            c.setBackground(new Color(248, 248, 248));
          } else {
            c.setBackground(Color.WHITE);
          }
        }
      }

      return c;
    }
  }

  /** Inner class to represent student statistics 学生统计信息内部类 */
  public static class StudentStatistics {
    private String name;
    private int signedDays;
    private int absentDays;
    private double attendanceRate;

    public StudentStatistics(String name, int signedDays, int absentDays) {
      this.name = name;
      this.signedDays = signedDays;
      this.absentDays = absentDays;
      this.attendanceRate = (double) signedDays / (signedDays + absentDays) * 100;
    }

    // Getters
    public String getName() {
      return name;
    }

    public int getSignedDays() {
      return signedDays;
    }

    public int getAbsentDays() {
      return absentDays;
    }

    public double getAttendanceRate() {
      return attendanceRate;
    }
  }
}
